#include "include.h"

SDL_Surface *ScreenGame = NULL;

SDL_Event ScreenGame2;

int ScreenX;
int ScreenY;
bool FullScreen;
bool DefaultResolution;

bool RunningGame = false;

using namespace std;
using std::vector;

int onMainGame()
{
	ifstream CheckFile(".\\settings.ini");
	if ( !CheckFile.is_open() )
	{
		int msok = MessageBox(NULL, "Can't find \"settings.ini\".", "Error", MB_OK | MB_ICONQUESTION );
		if ( msok )
		{
			int msyesno = MessageBox(NULL, "Do you want create settings?", "Request", MB_YESNOCANCEL | MB_ICONQUESTION );
			if ( msyesno == 6 )
			{ 
				ofstream CheckFile(".\\settings.ini");
				CheckFile << "[Graphics]\n";
				CheckFile << "ResolutionX=800\n";
				CheckFile << "ResolutionY=600\n";
				CheckFile << "Fullscreen=false\n";
			}
			else 
			{
				return 1;
			}
		}
	}

	CIniReader iniReader(".\\settings.ini");
	ScreenX = iniReader.ReadInteger("Graphics", "ResolutionX", 800);
	ScreenY = iniReader.ReadInteger("Graphics", "ResolutionY", 600);
	FullScreen = iniReader.ReadBoolean("Graphics", "Fullscreen", true);
	setScreenGame(ScreenX, ScreenY);

	if (ScreenX == 800 || ScreenY == 600) { DefaultResolution = true; }
	else { DefaultResolution = false; }

	if( SDL_Init( SDL_INIT_EVERYTHING ) == -1 )
	{
		MessageBox( NULL, "Can't run this game." , "ERROR", MB_OK | MB_ICONERROR );
		return 1;
	}
	else
	{
		SDL_WM_SetCaption( "G-Switch Online", NULL );
		SDL_WM_SetIcon( IMG_Load(".\\icon.ico"), NULL );
		if (FullScreen == true) { ScreenGame = SDL_SetVideoMode( ScreenX, ScreenY, 32, SDL_HWPALETTE|SDL_SWSURFACE|SDL_FULLSCREEN ); }
		else { ScreenGame = SDL_SetVideoMode( ScreenX, ScreenY, 32, SDL_HWPALETTE|SDL_SWSURFACE ); }
		if ( ScreenGame == NULL ) { MessageBox( NULL, "Can't create windows.", "Error", MB_OK | MB_ICONERROR ); return 1; }
		if ( TTF_Init() == -1 ) { return 1; }
	}

	const int FPS=30;
	Uint32 StartFPS;
	RunningGame = true;

	onEventsStart(ScreenGame);
	onFunctionsStart(ScreenGame);
	onMapsStart(ScreenGame);
	onGUIGameStart(ScreenGame);
	onDirectoryStart();
	onLoginStart();

	SDL_EnableUNICODE( 1 ) ;
	SDL_EnableKeyRepeat(250, SDL_DEFAULT_REPEAT_INTERVAL) ;

	while( RunningGame == true ) 
	{
		StartFPS = SDL_GetTicks();

		SDL_FillRect( ScreenGame, &ScreenGame->clip_rect, SDL_MapRGB(ScreenGame->format, 0xff, 0xff, 0xff) );

		drawText(0, 0, 255, 50, "G-Switch", ".\\data\\fonts\\font1.ttf", "center", 48, ScreenX/2, 50);

		LoginRender();

		while( SDL_PollEvent( &ScreenGame2 ) )
		{
			onGameEvents(ScreenGame2);
			LoginEvents(ScreenGame2);
		}

		if( RunningGame == false ) { LoginToggle(false); return 1; }
		if( SDL_Flip( ScreenGame ) == -1 ) { return 1; }
		if( 1000/FPS>(SDL_GetTicks()-StartFPS) ) { SDL_Delay(1000/FPS-(SDL_GetTicks()-StartFPS)); }
	}

	return 1;
}

void onMainGameStopping()
{
	RunningGame = false;
}